package com.topcent.tioxyc.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.ImgProcessEntity;
import com.topcent.tioxyc.pojo.vo.ImgProcessEntityResult;
import com.topcent.tioxyc.pojo.vo.InformationDateVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/7/29 15:51
 * @Description: 产品大图迁移数据控制类    跑一遍全部数据
 */
@Slf4j
@RestController
public class CcImgTestController {

    /**
     * 产品大图迁移数据接口
     *
     * @return
     */
    @GetMapping("dumpImgData")
    public String dumpImgData() throws IOException {
        String appId = "64ee9c37ee0a2c0007bc7afc";
        String entryId = "6694810ddb471c31112b395d";
        Header[] headers = ConnmeUtils.createHeaders();
        // 处理好产品大图拍摄申请数据分组后的数据
        List<ImgProcessEntity> imgProcessEntityList = processImgEntities(getImgProcessEntityList());
        // 处理好信息库营销资料上传申请数据
        List<InformationDateVO> informationDateVOList = getInformationDateVOList();

        // 1. 构建 informationDateVOList 的索引（产品型号+产品款式 → InformationDateVO）
        Map<String, InformationDateVO> infoIndex = informationDateVOList.stream()
                .filter(vo -> vo.get_widget_1721008397750() != null && vo.get_widget_1721008397751() != null)
                .collect(Collectors.toMap(
                        vo -> generateKey(vo.get_widget_1721008397750(), vo.get_widget_1721008397751()),
                        vo -> vo,
                        (existing, replacement) -> existing // 重复键保留第一个
                ));
        File outputImageOld = new File("E:/img/resultDumpImgData_" + System.currentTimeMillis() + ".png");
        //File outputImageOld = new File("/www/wwwroot/tupian/resultDumpImgData_" + System.currentTimeMillis() + ".png");
        // 2. 遍历 imgProcessEntityList，匹配并提取图片列表
        for (ImgProcessEntity imgEntity : imgProcessEntityList) {
            // 随机数
            String transactionId = IdUtil.randomUUID();

            // 生成匹配键（工作内容=产品型号，修改型号=产品款式）
            String imgKey = generateKey(
                    imgEntity.get_widget_1741762126396(),
                    imgEntity.get_widget_1741762126401()
            );

            InformationDateVO.infoDetailResult infoDetailResult = new InformationDateVO.infoDetailResult();
            infoDetailResult.set_widget_1721008397750(imgEntity.get_widget_1741762126396());
            infoDetailResult.set_widget_1721008397751(imgEntity.get_widget_1741762126401());
            // 提取上传源文件列表
            List<ImgProcessEntity.imgDetail> imgList = imgEntity.get_widget_1741763346076();
            if (imgList != null && !imgList.isEmpty()) {
                // 生成 token 和 url 及 图片
                List<String> returnImageList = returnImageList(imgList.getFirst().getUrl(), appId, entryId, headers, outputImageOld, transactionId);
                infoDetailResult.set_widget_1753952264330(returnImageList);
            }

            // 匹配信息库数据
            // 修改
            if (infoIndex.containsKey(imgKey)) {
                InformationDateVO informationDateVO = infoIndex.get(imgKey);
                infoDetailResult.set_id(informationDateVO.get_id());
                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", appId);
                parameterInster.put("entry_id", entryId);
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("transaction_id", transactionId);
                parameterInster.put("data_id", infoDetailResult.get_id());
                infoDetailResult.set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(infoDetailResult));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }else {
                // 新增
                Map<String, Object> parameter = new HashMap<>();
                parameter.put("app_id", appId);
                parameter.put("entry_id", entryId);
                parameter.put("transaction_id", transactionId);
                parameter.put("data", ConnmeUtils.convertEntityToMap(infoDetailResult));
                infoDetailResult.set_id(null);
                String jsonSale = JSONUtil.toJsonStr(parameter);
                System.out.println("接口返回: token and url ========》》》 " + infoDetailResult);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
            }
        }

        return "success: " + imgProcessEntityList.size();
    }

    // 获取产品大图拍摄申请数据
    public List<ImgProcessEntity> getImgProcessEntityList(){
        List<ImgProcessEntity> imgProcessEntityList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "64ee9c37ee0a2c0007bc7afc");
        parameter.put("entry_id", "650ab93189d8223244d5b4cc");

        /*Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);*/

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<ImgProcessEntity> list = JSONUtil.toList(objects, ImgProcessEntity.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            imgProcessEntityList.addAll(list);
        } while (fale);
        return imgProcessEntityList;
    }

    // 对数组进行分组处理
    public List<ImgProcessEntity> processImgEntities(List<ImgProcessEntity> imgProcessEntityList) {
        List<ImgProcessEntity> result = new ArrayList<>();

        // 循环前过滤：排除包含dept_no=127的实体（简化版）
        List<ImgProcessEntity> filteredEntities = imgProcessEntityList.stream()
                // 直接在filter中完成所有判断
                .filter(entity -> Optional.ofNullable(entity.get_widget_1700459876005())
                        .orElse(Collections.emptyList())
                        .stream()
                        .noneMatch(dept -> dept != null && "127".equals(dept.getDept_no())))
                .toList();

        for (ImgProcessEntity entity : filteredEntities) {
            // 1. 过滤掉 disabled 为“停用”的子表单
            List<ImgProcessEntity.subform> validSubforms = Optional.ofNullable(entity.getMx())
                    .orElse(Collections.emptyList())
                    .stream()
                    // 新增条件：style 不能为空（包括 null 和空字符串）
                    .filter(sub -> sub.getStyle() != null && !sub.getStyle().trim().isEmpty())
                    .filter(sub -> sub.getDisabled() == null || !"停用".equals(sub.getDisabled())).toList();

            // 2. 按 product_name 和 specifications_model 分组
            Map<String, List<ImgProcessEntity.subform>> groupedSubforms = validSubforms.stream()
                    .collect(Collectors.groupingBy(sub -> {
                        // 生成分组键（处理 null 情况）
                        String productName = sub.getImgnames() == null ? "" : sub.getImgnames();
                        String specModel = sub.getStyle() == null ? "" : sub.getStyle();
                        return productName + "|" + specModel;
                    }));

            // 3. 处理每个分组，生成新的 ImgProcessEntity
            for (Map.Entry<String, List<ImgProcessEntity.subform>> entry : groupedSubforms.entrySet()) {
                ImgProcessEntity processedEntity = new ImgProcessEntity();
                List<ImgProcessEntity.subform> group = entry.getValue();
                // 取分组中第一个子表单的基础信息（因分组键相同，字段值一致）
                ImgProcessEntity.subform firstSub = group.getFirst();

                // 赋值工作内容（product_name）
                processedEntity.set_widget_1741762126396(firstSub.getImgnames());
                // 赋值修改型号（specifications_model）
                processedEntity.set_widget_1741762126401(firstSub.getStyle());
                // 合并所有子表单的加工后图（appendix）到上传源文件字段
                List<ImgProcessEntity.imgDetail> mergedAppendix = group.stream()
                        .flatMap(sub -> Optional.ofNullable(sub.getAppendix()).orElse(Collections.emptyList()).stream())
                        .collect(Collectors.toList());
                processedEntity.set_widget_1741763346076(mergedAppendix);

                result.add(processedEntity);
            }
        }

        return result;
    }

    // 获取信息库营销资料上传申请数据
    public List<InformationDateVO> getInformationDateVOList(){
        List<InformationDateVO> informationDateVOList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "64ee9c37ee0a2c0007bc7afc");
        parameter.put("entry_id", "6694810ddb471c31112b395d");

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<InformationDateVO> list = JSONUtil.toList(objects, InformationDateVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            informationDateVOList.addAll(list);
        } while (fale);
        return informationDateVOList;
    }

    /**
     * 生成复合键（将多个字段拼接为唯一字符串）
     * @param parts 多个字段（如产品型号、产品款式等）
     * @return 拼接后的唯一键（格式："字段1|字段2|..."）
     */
    private String generateKey(String... parts) {
        // 用分隔符"|"拼接，避免不同字段组合产生歧义（如"AB"+"C"和"A"+"BC"的区别）
        return String.join("|", parts);
    }

    /**
     * 生成token 和 url
     *
     * @param appId
     * @param entryId
     * @param transactionId
     * @return
     */
    public JSONArray getUploadToken(String appId, String entryId, String transactionId, Header[] headers) {
        Map<String, Object> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("entry_id", entryId);
        params.put("transaction_id", transactionId);

        String jsonSale = JSONUtil.toJsonStr(params);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/file/get_upload_token", headers, jsonSale);
        // 直接从响应中获取 token_and_url_list
        JSONArray tokenAndUrlList = jdySale.getJSONArray("token_and_url_list");

        if (tokenAndUrlList != null && !tokenAndUrlList.isEmpty()) {
            // 如果数组不为空，获取第一个元素
            return tokenAndUrlList;  // 返回 token 和 url
        } else {
            // 如果数组为空，抛出异常或返回 null
            throw new RuntimeException("No tokens available in token_and_url_list");
        }

    }
    /**
     * 生成 key
     * @param uploadUrl
     * @param token
     * @param imageFile
     * @return
     */
    public String uploadImage(String uploadUrl, String token, File imageFile) {
        String response = HttpRequest.post(uploadUrl)
                .form("token", token)
                .form("file", imageFile, imageFile.getName())  // Upload the image file
                .form("filename", imageFile.getName())  // The filename
                .execute()
                .body();

        JSONObject jsonResponse = JSONUtil.parseObj(response);
        System.out.println("生成key ========++++++》》》 " + jsonResponse);
        return jsonResponse.getStr("key");  // 返回的 key
    }

    /**
     * 生成 List<String>
     * @param
     * @return
     */
    public List<String> returnImageList(String uploadUrl, String appId, String entryId,  Header[] headers, File outputImageOld, String transactionId) throws IOException {
        List<String> imgaList = new ArrayList<>();
        // 上传图片到简道云
        JSONObject uploadToken = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(0);
        URL imageUrl = new URL(uploadUrl);
        InputStream inputStreamOld = imageUrl.openStream();
        BufferedImage imageOld = ImageIO.read(inputStreamOld);
        if (imageOld == null) {
            log.error("图像加载失败，image为null");
            return null; // 或其他合理处理
        }
        ImageIO.write(imageOld, "png", outputImageOld);
        String newUrl = uploadImage(uploadToken.getStr("url"), uploadToken.getStr("token"), outputImageOld);
        imgaList.add(newUrl);
        return imgaList;
    }




    /**
     * 产品大图赋值图片数据接口
     *
     * @return
     */
    @GetMapping("dumpImgAssignmentData")
    public String dumpImgAssignmentData() throws IOException {
        String appId = "64ee9c37ee0a2c0007bc7afc";
        String entryId = "650ab93189d8223244d5b4cc";
        Header[] headers = ConnmeUtils.createHeaders();
        // 产品大图拍摄申请数据
        List<ImgProcessEntity> imgProcessEntityList = getImgProcessEntityList();
        // 随机数
        String transactionId = IdUtil.randomUUID();
        File outputImageOld = new File("E:/img/resultDumpImgData_" + System.currentTimeMillis() + ".png");
        for(ImgProcessEntity imgProcessEntity : imgProcessEntityList){
            ImgProcessEntityResult entityResult =new ImgProcessEntityResult();
            List<ImgProcessEntityResult.subformResult> subformResultList = new ArrayList<>();
            for(ImgProcessEntity.subform subform : imgProcessEntity.getMx()){
                ImgProcessEntityResult.subformResult subformResult = new ImgProcessEntityResult.subformResult();
                // 提取产品加工后图
                List<ImgProcessEntity.imgDetail> imgList = subform.getAppendix();
                List<String> returnImageList = imageHandleMethod(imgList, appId, entryId, transactionId, headers, outputImageOld);
                subformResult.setAppendix(returnImageList); // 产品大图
                subformResult.set_widget_1754458627927(returnImageList); //产品大图销售报价用

                // 提取白色底图
                List<ImgProcessEntity.imgDetail> imgList1 = subform.get_widget_1747808645559();
                List<String> returnImageList1 = imageHandleMethod(imgList1, appId, entryId, transactionId, headers, outputImageOld);
                subformResult.set_widget_1747808645559(returnImageList1); // 白色底图

                // 2. 处理原始产品大图（_widget_1700546383563）
                List<ImgProcessEntity.imgDetail> originalImgList = subform.get_widget_1700546383563();
                List<String> originalImgKeys = imageHandleMethod(originalImgList, appId, entryId, transactionId, headers, outputImageOld);
                subformResult.set_widget_1700546383563(originalImgKeys); // 原始产品大图

                // 3. 处理拍摄大图（appendix_tu）
                List<ImgProcessEntity.imgDetail> shotImgList = subform.getAppendix_tu();
                List<String> shotImgKeys = imageHandleMethod(shotImgList, appId, entryId, transactionId, headers, outputImageOld);
                subformResult.setAppendix_tu(shotImgKeys); // 拍摄大图

                // 4. 处理渲染大图（_widget_1722483118806）
                List<ImgProcessEntity.imgDetail> renderImgList = subform.get_widget_1722483118806();
                List<String> renderImgKeys = imageHandleMethod(renderImgList, appId, entryId, transactionId, headers, outputImageOld);
                subformResult.set_widget_1722483118806(renderImgKeys); // 渲染大图

                subformResult.setDisabled(subform.getDisabled());
                subformResult.setImgnames(subform.getImgnames());
                subformResult.setSub_process_code(subform.getSub_process_code());
                subformResult.setStyle(subform.getStyle());
                subformResult.setProduct_name(subform.getProduct_name());
                subformResult.setProduct_grade(subform.getProduct_grade());
                subformResult.setProduct_key_points(subform.getProduct_key_points());
                subformResult.setProvided_samples(subform.getProvided_samples());
                subformResult.setUnit(subform.getUnit());
                subformResult.setShooting_requirements_remarks(subform.getShooting_requirements_remarks());
                subformResult.setNeed_to_include_in_catalog(subform.getNeed_to_include_in_catalog());
                subformResult.setSupplier_material_available(subform.getSupplier_material_available());
                subformResult.setSupplier_material_storage_path(subform.getSupplier_material_storage_path());
                subformResult.setSpecifications_model(subform.getSpecifications_model());
                subformResult.setTransfer(subform.getTransfer());
                subformResultList.add(subformResult);
            }
            entityResult.setMx(subformResultList);
            // Step 5: Update form with image key
            updateFormData(imgProcessEntity, appId, entryId, transactionId, headers, entityResult);
            System.out.println("接口返回: token and url ========》》》 " + entityResult);
        }
        return "success: " + imgProcessEntityList.size();
    }

    /**
     * 上传简道云
     * @param appId
     * @param entryId
     * @param entityResult
     * @param transactionId
     */
    public void updateFormData(ImgProcessEntity entity, String appId, String entryId, String transactionId, Header[] headers , ImgProcessEntityResult entityResult) {
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", appId);
        parameterInster.put("entry_id", entryId);
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", entity.get_id());
        parameterInster.put("transaction_id", transactionId);
        entityResult.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(entityResult));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        log.info("图片处理的数据{}", jsonSalee);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    /**
     * 图片处理方法：循环生成
     * @param imageList
     * @param appId
     * @param entryId
     * @param transactionId
     * @param headers
     */
    public List<String> imageHandleMethod(List<ImgProcessEntity.imgDetail> imageList, String appId, String entryId, String transactionId, Header[] headers , File outputImageOld) throws IOException {
        // 提取原始产品大图
        List<String> returnImageList = new ArrayList<>();
        if (imageList != null && !imageList.isEmpty()) {
            for (ImgProcessEntity.imgDetail imgDetail : imageList) {
                // 生成 token 和 url 及 图片
                returnImageList.add(
                        Optional.ofNullable(returnImageList(imgDetail.getUrl(), appId, entryId, headers, outputImageOld, transactionId))
                                .filter(list -> !list.isEmpty())
                                .map(List::getFirst)
                                .orElse(null) // 或根据需求返回默认值，如空字符串
                );
            }
        }
        return returnImageList;
    }

}
